package com.bondar.task4;

public class CircularExecutor { 
    private volatile int currentThreadNumber; 
    private Thread[] threads; 
 
 
    public int getCurrentThreadNumber() { 
        return currentThreadNumber; 
    } 
 
    public synchronized void next() { 
        if (currentThreadNumber == threads.length - 1) 
            currentThreadNumber = 0; 
        else 
            currentThreadNumber++; 
    } 
 
    public static void main(String[] args) { 
        CircularExecutor circularExecutor = new CircularExecutor(); 
        circularExecutor.threads = new Thread[3]; 
 
        for (int i = 0; i < 3; i++) { 
            circularExecutor.threads[i] = new Thread(new MyThread(i, circularExecutor)); 
            circularExecutor.threads[i].start(); 
        } 
    } 
} 
 
 
class MyThread implements Runnable { 
 
    private CircularExecutor circularExecutor; 
    private int threadNumber; 
 
    public MyThread(int threadNumber, CircularExecutor circularExecutor) { 
        this.threadNumber = threadNumber; 
        this.circularExecutor = circularExecutor;
    } 
 
    public int getThreadNumber() { 
        return threadNumber; 
    } 
 
    @Override 
    public void run() { 
        while (true) { 
        	synchronized (circularExecutor) { 
        		while (circularExecutor.getCurrentThreadNumber() != threadNumber) { 
                    try { 
                        circularExecutor.wait(); 
                    } catch (InterruptedException e) { 
                        e.printStackTrace(); 
                    } 
            	} 
            } 
 
            try { 
            	System.out.println(threadNumber);
                Thread.sleep(1000); 
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            } 
 
            synchronized (circularExecutor) { 
            	circularExecutor.next(); 
            	circularExecutor.notifyAll(); 
            } 
 
        } 
    } 
 
}